/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import bean.AddProviderBean;
import bean.LoginActionFormBean;
import bean.SearchSupplierBean;
import dao.ActivityHistoryCrud;
import dao.ProviderDao;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.AddProvider;
import model.EditProvider;
//import model.ScheduleTaskWindows;
import model.LogFile;
import model.OSDetector;
import model.ScheduledTaskLinux;
import model.ScheduledTaskOperations;
import model.ScheduledTaskWindows;
import model.SearchSupplier;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import pojo.Activities;
import pojo.ActivityHistory;
import pojo.FtpInfo;
import pojo.Provider;
import pojo.Scheduledata;

/**
 *
 * @author A7med Kotb
 */
//class to edit in the provider profile
public class EditProfile extends org.apache.struts.actions.DispatchAction 
{

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    
    public ActionForward Edit(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        String providerName=request.getParameter("name");
        EditProvider ep=new EditProvider(getDataSource(request, "MyDS").getConnection());
        Provider pro=ep.generalInfo(providerName);
        request.setAttribute("generalinfo", pro);
        
        FtpInfo ftpinfo=ep.ftpinformaion(pro.getPId());
        request.setAttribute("ftpinfo",ftpinfo);
        
        Scheduledata sc=ep.scheduleInformation(pro.getPId());
        request.setAttribute("scheduledata", sc);
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        String reportDate = df.format(sc.getStartDate());
        System.out.println("reportDate is Equal to "+reportDate);
        request.setAttribute("startdate",reportDate);
        return mapping.findForward(SUCCESS);
    }
    
    //this method to update provider profile data
    public ActionForward Update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        LoginActionFormBean loginbean=(LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        AddProviderBean mybean=(AddProviderBean)form;
        Provider prov=new Provider();
        prov.setName(mybean.getProviderName());
        prov.setType(mybean.getType());
        prov.setTableName(mybean.getTableName());
        prov.setScriptPath(mybean.getScriptPath());
        EditProvider ep=new EditProvider(getDataSource(request, "MyDS").getConnection());
        boolean genralresult=ep.updateGeneral(prov);
        
        
        FtpInfo ftpinfo=new FtpInfo();
        ftpinfo.setHost(mybean.getHost());
        ftpinfo.setRemoteDir(mybean.getRemoteDir());
        ftpinfo.setFileName(mybean.getFileName());
        ftpinfo.setFileExtension(mybean.getFileExtension());
        ftpinfo.setUserName(mybean.getUserName());
        ftpinfo.setPassword(mybean.getPassword());
        ftpinfo.setDateMod(mybean.getDownloadDate());
        ftpinfo.setLocalDir(mybean.getLocalDir());
        boolean ftpresult=ep.updateFtp(ftpinfo,prov);
        
        Scheduledata scdata=new Scheduledata();
        scdata.setSchedule(mybean.getSchedule());
        scdata.setModifier(mybean.getModifier());
        scdata.setStartDate(mybean.getStartDated());
        scdata.setStartTime(mybean.getStartTime());
        String[] selectedDays = mybean.getDay();
        String days = "";
        for (int i = 0; i < selectedDays.length; i++) {
            days += selectedDays[i] + ",";
        }
        int strlen = days.length();
        int lastindex = strlen - 1;
        String taskdays = days.substring(0, lastindex);
        scdata.setDay(taskdays);
        boolean scheduleresult=ep.updateschedule(scdata,prov);
        
        Provider mypro=ep.generalInfo(mybean.getProviderName());
        boolean deletetask=false;
        boolean createtask=false;
        if(OSDetector.isWindows()){
            deletetask=new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).deleteAfterUpdate(mypro.getPId());
            createtask=new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).create(scdata,prov.getName());
        }
        if(OSDetector.isUnix()){
            deletetask=new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).delete(mypro.getPId());
            createtask=new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).create(scdata,prov.getName());
        }
        boolean logresult=activityHistory("Edit Provider Profile", request, mypro.getPId());
        if(logresult == true)
        {
            LogFile.log(" System "," Logged the operation of updating profile of the provider "+mybean.getProviderName());
        }
        else
        {
            LogFile.log(" System "," failed to log the operation of updating profile of the provider "+mybean.getProviderName());
        }
        if(deletetask==true&&createtask==true&&genralresult==true&&ftpresult==true&&scheduleresult==true)
        {
            LogFile.log(loginbean.getUserName(),"updated profile data of the provider "+mybean.getProviderName());
        }
        else
        {
            LogFile.log(" System "," failed to update profile data of the provider "+mybean.getProviderName());
        }
        return mapping.findForward("update");
    }
    
    public ActionForward Found(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        
        System.out.println("Helloooooo I am inside action now ");
        AddProviderBean ssb=(AddProviderBean)form;
        String param=ssb.getParameter();
        int acclevel=Integer.parseInt(ssb.getAccuracyLevel());
        SearchSupplier ss=new SearchSupplier();
        //Vector<Provider> pro=ss.searchProvider(param, acclevel);
//        System.out.println("Vector Size is ////////////////////////="+pro.size());
//        request.setAttribute("myvect",pro);
        return mapping.findForward("search");
    }
    
     public ActionForward Show(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
//        System.out.println("heloooooooooooooooooooooooooooooooooooooooooooooo");
//        SearchSupplierBean apb=(SearchSupplierBean)form;
//        String providerName=apb.getProviderName();
//        EditProvider ep=new EditProvider();
//        Provider pro=ep.generalInfo(providerName);
//        
////        FtpInfo ftpinfo=ep.ftpinformaion(pro.getPId());
////        request.setAttribute("ftpinfo",ftpinfo);
//        
//        Scheduledata sc=ep.scheduleInformation(pro.getPId());
//        request.setAttribute("scheduledata", sc);
        return mapping.findForward("task");
    }
   
  public ActionForward Display(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        EditProvider edprov=new EditProvider(getDataSource(request, "MyDS").getConnection());
        Vector<Provider> myvect=edprov.getAll();
        request.setAttribute("Names", myvect);             
        return mapping.findForward("display");
    }
  
  //this method is to delete existing provider
    public ActionForward Delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        String providerName=request.getParameter("name");
        LoginActionFormBean loginbean=(LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        EditProvider ep=new EditProvider(getDataSource(request, "MyDS").getConnection());
        Provider pro=ep.generalInfo(providerName);
        boolean logresult=activityHistory("Delete Provider", request, pro.getPId());
        boolean deleteresult=new ScheduledTaskOperations(getDataSource(request, "MyDS").getConnection()).delete(pro.getPId());
        boolean deletedbresult=ep.deleteProvider(providerName,pro.getPId());
        if(logresult == true)
        {
            LogFile.log(" System "," Logged the operation of deleting the provider "+pro.getName());
        }
        else
        {
            LogFile.log(" System "," failed to log the operation of deleting the provider "+pro.getName());
        }
        if(deleteresult == true && deletedbresult == true )
        {
            LogFile.log(loginbean.getUserName(),"deleted the provider "+pro.getName()+"from our providers list");
        }
        else
        {
            LogFile.log(" System "," failed to delete the provider  "+pro.getName() +"from database");
        }
        ActionForward forward=new ActionForward();
        return forward=Display(mapping, form, request, response);
    } 
    
 
    //Add Activity to Activity History
    public boolean activityHistory(String activityName ,HttpServletRequest request , int taskid)
    {
        boolean check=false;
        try 
        {
            LoginActionFormBean loginbean= (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
            ActivityHistory log= new ActivityHistory();
            log.setAdminName(loginbean.getUserName());
            ProviderDao pdao=new ProviderDao(getDataSource(request, "MyDS").getConnection());
            Provider pro=pdao.getById(taskid);
            log.setProviderName(pro.getName());
            log.setStatus("Success");
            log.setLiveServer(null);
            ActivityHistoryCrud ahc = new ActivityHistoryCrud(getDataSource(request, "MyDS").getConnection());
            Activities act=ahc.getByName(activityName);
            log.setActivities(act);
            log.setActivityName(act.getName());
            check=ahc.add(log);
        }
        catch (SQLException ex) 
        {
            Logger.getLogger(STOperations.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception while trying to log this action "+ex.getMessage());
            check=false;
        }
        return check;
    }
}
